package com.ruoyi.course.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysPeriod;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.course.mapper.SysPeriodMapper;
import com.ruoyi.course.service.ISysPeriodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课时管理 服务实现
 * 
 * @author YJF
 */
@Service
public class SysPeriodServiceImpl implements ISysPeriodService
{
    @Autowired
    private SysPeriodMapper periodMapper;


    /**
     * 查询课时管理数据
     * 
     * @param period 课时信息
     * @return 课时信息集合
     */
    @Override
    @DataScope(periodAlias = "d")
    public List<SysPeriod> selectPeriodList(SysPeriod period)
    {
        return periodMapper.selectPeriodList(period);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param periods 课时列表
     * @return 树结构列表
     */
    @Override
    public List<SysPeriod> buildPeriodTree(List<SysPeriod> periods)
    {
        List<SysPeriod> returnList = new ArrayList<SysPeriod>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysPeriod period : periods)
        {
            tempList.add(period.getPeriodId());
        }
        for (SysPeriod period : periods)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(period.getParentId()))
            {
                recursionFn(periods, period);
                returnList.add(period);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = periods;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param periods 课时列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildPeriodTreeSelect(List<SysPeriod> periods)
    {
        List<SysPeriod> periodTrees = buildPeriodTree(periods);
        return periodTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据课时ID查询信息
     * 
     * @param periodId 课时ID
     * @return 课时信息
     */
    @Override
    public SysPeriod selectPeriodById(Long periodId)
    {
        return periodMapper.selectPeriodById(periodId);
    }

    /**
     * 根据ID查询所有子课时（正常状态）
     * 
     * @param periodId 课时ID
     * @return 子课时数
     */
    @Override
    public int selectNormalChildrenPeriodById(Long periodId)
    {
        return periodMapper.selectNormalChildrenPeriodById(periodId);
    }

    /**
     * 是否存在子节点
     * 
     * @param periodId 课时ID
     * @return 结果
     */
    @Override
    public boolean hasChildByPeriodId(Long periodId)
    {
        int result = periodMapper.hasChildByPeriodId(periodId);
        return result > 0;
    }

    /**
     * 查询课时是否存在课程
     * 
     * @param periodId 课时ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkPeriodExistCourse(Long periodId)
    {
        int result = periodMapper.checkPeriodExistCourse(periodId);
        return result > 0;
    }

    /**
     * 校验课时名称是否唯一
     * 
     * @param period 课时信息
     * @return 结果
     */
    @Override
    public String checkPeriodNameUnique(SysPeriod period)
    {
        Long periodId = StringUtils.isNull(period.getPeriodId()) ? -1L : period.getPeriodId();
        SysPeriod info = periodMapper.checkPeriodNameUnique(period.getPeriodName(), period.getParentId());
        if (StringUtils.isNotNull(info) && info.getPeriodId().longValue() != periodId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验课时是否有数据权限
     * 
     * @param periodId 课时id
     */
    @Override
    public void checkPeriodDataScope(Long periodId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysPeriod period = new SysPeriod();
            period.setPeriodId(periodId);
            List<SysPeriod> periods = SpringUtils.getAopProxy(this).selectPeriodList(period);
            if (StringUtils.isEmpty(periods))
            {
                throw new ServiceException("没有权限访问课时数据！");
            }
        }
    }

    /**
     * 新增保存课时信息
     * 
     * @param period 课时信息
     * @return 结果
     */
    @Override
    public int insertPeriod(SysPeriod period)
    {
        SysPeriod info = periodMapper.selectPeriodById(period.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("课时停用，不允许新增");
        }
        period.setAncestors(info.getAncestors() + "," + period.getParentId());
        return periodMapper.insertPeriod(period);
    }

    /**
     * 修改保存课时信息
     * 
     * @param period 课时信息
     * @return 结果
     */
    @Override
    public int updatePeriod(SysPeriod period)
    {
        SysPeriod newParentPeriod = periodMapper.selectPeriodById(period.getParentId());
        SysPeriod oldPeriod = periodMapper.selectPeriodById(period.getPeriodId());
        if (StringUtils.isNotNull(newParentPeriod) && StringUtils.isNotNull(oldPeriod))
        {
            String newAncestors = newParentPeriod.getAncestors() + "," + newParentPeriod.getPeriodId();
            String oldAncestors = oldPeriod.getAncestors();
            period.setAncestors(newAncestors);
            updatePeriodChildren(period.getPeriodId(), newAncestors, oldAncestors);
        }
        int result = periodMapper.updatePeriod(period);
        if (UserConstants.DEPT_NORMAL.equals(period.getStatus()) && StringUtils.isNotEmpty(period.getAncestors())
                && !StringUtils.equals("0", period.getAncestors()))
        {
            // 如果该课时是启用状态，则启用该课时的所有上级课时
            updateParentPeriodStatusNormal(period);
        }
        return result;
    }

    /**
     * 修改该课时的父级课时状态
     * 
     * @param period 当前课时
     */
    private void updateParentPeriodStatusNormal(SysPeriod period)
    {
        String ancestors = period.getAncestors();
        Long[] periodIds = Convert.toLongArray(ancestors);
        periodMapper.updatePeriodStatusNormal(periodIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param periodId 被修改的课时ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updatePeriodChildren(Long periodId, String newAncestors, String oldAncestors)
    {
        List<SysPeriod> children = periodMapper.selectChildrenPeriodById(periodId);
        for (SysPeriod child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            periodMapper.updatePeriodChildren(children);
        }
    }

    /**
     * 删除课时管理信息
     * 
     * @param periodId 课时ID
     * @return 结果
     */
    @Override
    public int deletePeriodById(Long periodId)
    {
        return periodMapper.deletePeriodById(periodId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysPeriod> list, SysPeriod t)
    {
        // 得到子节点列表
        List<SysPeriod> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysPeriod tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysPeriod> getChildList(List<SysPeriod> list, SysPeriod t)
    {
        List<SysPeriod> tlist = new ArrayList<SysPeriod>();
        Iterator<SysPeriod> it = list.iterator();
        while (it.hasNext())
        {
            SysPeriod n = (SysPeriod) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getPeriodId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysPeriod> list, SysPeriod t)
    {
        return getChildList(list, t).size() > 0;
    }
}
